import { Button, Icon, Input, Tooltip } from 'antd';
import React from 'react';

const getEffectParams = (values: any) => {
  const keys = Object.keys(values);
  const effectParams: any = {};
  keys.forEach(key => {
    if (Array.isArray(values[key]) && key === 'range-time-picker') {
      const [startTime = '', endTime = ''] = Array.isArray(values[key])
        ? values[key].map((item: any) => item.format('YYYY-MM-DD HH:mm:ss'))
        : [];
      effectParams.startTime = startTime;
      effectParams.endTime = endTime;
    } else if (Array.isArray(values[key]) && key !== 'range-time-picker') {
      effectParams[key] = values[key].join();
    } else if (!Array.isArray(values[key]) && values[key] !== 'undefind') {
      effectParams[key] = values[key];
    }
  });
  return effectParams;
};

// 去除请求参数中的空格
export const handleDeleteSpace = (effectParams: any) => {
  Object.keys(effectParams).forEach((item: any) => {
    if (typeof effectParams[item] === 'string') {
      if (item !== 'startTime' && item !== 'endTime') {
        effectParams[item] = effectParams[item].replace(/\s+/g, '');
      }
    }
  });
  return effectParams;
};

export function getErrTip(val: boolean) {
  let tip = {
    timeTip: {},
    orderIdTip: {},
  };
  if (val) {
    tip = {
      timeTip: {
        help: '请选择提交时间',
        validateStatus: 'error',
      },
      orderIdTip: {
        help: '请输入充值单号',
        validateStatus: 'error',
      },
    };
  }
  return tip;
}

// 统一表格列宽度
export const initTabWidth = (columns: any, width: any = 130) => {
  columns.forEach((item: any) => {
    item.width = width;
  });
};

/*
 * 给定字符串长度，返回省略样式的元素节点
 * @param [String] str: 需要处理的字符串
 * @param [Number] width: 需要限制的长度
 */
export function getElliStyleElement(str: string, width: number = 130): ReactNode {
  const style: CSSProperties = {
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
    width: width - 17,
    margin: 'auto',
  };

  return (
    <Tooltip title={str}>
      <div style={style}> {str} </div>
    </Tooltip>
  );
}

export function setCommonFun(target: any): any {
  return class extends target {
    // state = {
    public errTip: any = false;

    public dataBoolean: any = false;

    public inputBoolean: any = true;
    // };

    // 表单提交处理
    setSubmitFormatParams = (values: any) => {
      const effectParams = getEffectParams(values);
      if (this.name === 'PaymentComponent' || this.name === 'HistoryComponent') {
        if (effectParams.orderId) {
          delete effectParams.startTime;
          delete effectParams.endTime;
        }
      }
      // 会员查询--交易明细，查询参数加上userId
      if (this.name === 'levelAdjustment' || this.name === 'trsdeDetailsComponent') {
        effectParams.userId = this.state.effectParams.userId;
      }
      return handleDeleteSpace(effectParams);
    };

    // 重置表单查询
    resetForm = () => {
      this.dataBoolean = false;
      this.inputBoolean = true;
      this.errTip = false;

      this.props.form.resetFields();
      this.props.form.validateFieldsAndScroll(async (err: any, values: any) => {
        const effectParams = getEffectParams(values);
        if (this.name === 'levelAdjustment' || this.name === 'trsdeDetailsComponent') {
          effectParams.userId = this.state.effectParams.userId;
        }
        const object = handleDeleteSpace(effectParams);
        await this.setState({
          effectParams: object,
        });
        await this.refMtable.bindEffects();
      });
    };

    // 时间和单号，强制二选一
    handleFormChange = (newValue: any) => {
      if (Array.isArray(newValue)) {
        this.dataBoolean = !newValue.length;
      } else {
        const { value } = newValue.target;
        this.inputBoolean = !value;
      }
      this.errTip = this.dataBoolean && this.inputBoolean;
    };
  };
}

export const getColumnSearchProps = (
  dataIndex: string,
  self: any,
  placeholder: string = '搜索',
) => ({
  filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }: any) => (
    <div style={{ padding: 8 }}>
      <Input
        ref={node => {
          self.searchInput = node;
        }}
        placeholder={placeholder}
        value={selectedKeys[0]}
        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
        onPressEnter={() => confirm()}
        style={{ width: 188, margin: '0 auto', marginBottom: 8, display: 'block' }}
      />
      <Button
        type="primary"
        onClick={async () => {
          confirm();
        }}
        icon="search"
        size="small"
        style={{ width: 90, margin: 0 }}
      >
        搜索
      </Button>
      <Button
        onClick={() => {
          clearFilters();
          confirm();
        }}
        size="small"
        style={{ width: 90, marginLeft: 8 }}
      >
        重置
      </Button>
    </div>
  ),
  filterIcon: (filtered: any) => (
    <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
  ),
});

export const withdrawStatusMap = {
  '-3': '风险待审核',
  '-2': '风险审核拒绝',
  0: '风险审核通过（待出款）',
  1: '出款成功',
  2: '拒绝出款（出款失败）',
  3: '申请退回中',
  4: '退回成功',
  5: '拒绝退回',
  6: '申请强制成功中',
  7: '自动出款失败',
  8: '通过强制成功',
  9: '拒绝强制成功',
  10: '三方自动出款中',
  11: '出款专员处理中',
};
